#!/usr/bin/env python
# -*- coding: utf-8 -*-
from threading import *
import os
import random
import tempfile
import logging
import wx
from upload_video import *
import sys
import math
import overlay
from ctypes import *
import string
from osdependent_func import *
class VideoGenerator(Thread):
	#iteration = -1 means infinite iteration
	def __init__(self, notify_window=None,iteration=2,preroll="preroll",main="main",close1="close1",close2="close2",output_dir = "output",
					audio="audio",no_of_main_image=1,mdfilename="mdfilename.txt",categoryID="25",Title="Test Title",
					Description="Description",KeyWord="Keyword",overlayInfo=overlay.dInfo,edir="",
					preroll_min=5,preroll_max=5,main_min=5,main_max=5,close1_min=5,close1_max=5,close2_min=5,close2_max=5):
		Thread.__init__(self)
		#notify window is the class that has created this thread
		self._notify_window = notify_window
		self._want_abort = 0
		#no of video to be proccessed
		self._iteration = iteration
		self.edir = edir
		self.font_file = os.path.join(self.edir ,"font","arialbd.ttf")

		self.font_file = self.font_file.replace("\\","\\\\")
		self.font_file = self.font_file.replace(":","\\:")
		self.font_file = "\'" + self.font_file + "\'"

		preroll = os.path.abspath(preroll)
		main = os.path.abspath(main)
		if close1 != None:
			close1 = os.path.abspath(close1)
		close2 = os.path.abspath(close2)
		audio = os.path.abspath(audio)
		self.preroll = preroll
		self.main    = main
		self.close1  = close1
		self.close2  = close2
		self.audio = audio
		self.no_of_main_image = no_of_main_image
		self.mdfilename = mdfilename
		self.output_dir = output_dir
		self.Title = Title
		self.Description = Description
		self.KeyWord = KeyWord
		self.categoryID = categoryID
		self.app_thread_exit = 0
		self.overlayInfo = overlayInfo
		self.lock = RLock()
		os.environ['PATH'] = self.edir + ';' + os.environ['PATH']
		self.lib = load_library("libOverlay")
		self.lib_ctx = None
		self.preroll_min = preroll_min
		self.preroll_max = preroll_max
		self.main_min = main_min
		self.main_max = main_max
		self.close1_min = close1_min
		self.close1_max = close1_max
		self.close2_min = close2_min
		self.close2_max = close2_max

		#Starting thread as soon as created
		self.start()

	def select_ran_music(self,directory):
		count = 0
		music_list = []
		ran_list = []
		files = os.listdir(directory)
		for var in files:
			if var.endswith('.mp3' ) or var.endswith('.wav'):
				music_list.append(os.path.join(directory ,var))

		selected = music_list[random.randint(0,len(music_list) - 1)]
		return selected

	def add_phase(self,dest_dir,overlay_text,img_count,min_time,max_time,textcolor,textx,texty,shadowcolor,shadowx,shadowy):
		ret = self.lib.add_phase(self.lib_ctx,c_char_p (dest_dir),
				c_char_p (overlay_text),c_int(img_count),
				c_int(min_time), c_int(max_time),
				c_int(textcolor),c_int(textx),c_int(texty),
				c_int(shadowcolor),
				c_int(shadowx),
				c_int(shadowy))
		if(ret < 0):
			logging.error("Unable to add phase")

	def set_audio(self,audio):
		ret = self.lib.set_audio(self.lib_ctx,c_char_p (audio))
		if ret < 0:
			logging.error("Unable to set audio")
	def run(self):
		i = 0
		fo = open(self.mdfilename,"r")
		#actual video generation

		for loop in fo:
			with self.lock:
				if(self.app_thread_exit):
					break

			if i >= self._iteration and self._iteration != -1:
				break

			L = []
			for word in loop.split("\t"):
				L.append(word)

			loop = loop.replace("\n", "")
			loop = loop.replace("\r", "")
			loop = loop.replace("\t", " ")


			try:
				md1=L[0]
			except:
				md1=""
				
			try:
				md2=L[1]
			except:
				md2=""
				
			try:
				md3=L[2]
			except:
				md3=""
				
			try:
				md4=L[3]
			except:
				md4=""
			
			md1_ = md1.replace(" ","_")
			md2_ = md2.replace(" ","_")
			md3_ = md3.replace(" ","_")
			md4_ = md4.replace(" ","_")
			output_name = os.path.join(self.output_dir,md1_ + "_" + md2_ + "_" + md3_ + "_" + md4_) 
			output_name = output_name.replace("\n\r",".mp4")
			output_name = output_name.replace("\r\n",".mp4")
			output_name = output_name.replace("\n\n",".mp4")
			output_name = output_name.replace("\n",".mp4")

			md4 = md4.replace("\n\r","")
			md4 = md4.replace("\n","")
			md4 = md4.replace("\f","")
			md4 = md4.replace("\r","")

			cTitle = self.Title
			#Adapt Title, keyword, Description
			cTitle = cTitle.replace("{ click md1 button }",md1)
			cTitle = cTitle.replace("{ click md2 button }",md2)
			cTitle = cTitle.replace("{ click md3 button }",md3)
			cTitle = cTitle.replace("{ click md4 button }",md4)
			
			cDescription = self.Description
			cDescription = cDescription.replace("{ click md1 button }",md1)
			cDescription = cDescription.replace("{ click md2 button }",md2)
			cDescription = cDescription.replace("{ click md3 button }",md3)
			cDescription = cDescription.replace("{ click md4 button }",md4)
			
			cKeyWord = self.KeyWord
			cKeyWord = cKeyWord.replace("{ click md1 button }",md1)
			cKeyWord = cKeyWord.replace("{ click md2 button }",md2)
			cKeyWord = cKeyWord.replace("{ click md3 button }",md3)
			cKeyWord = cKeyWord.replace("{ click md4 button }",md4)

			key_list = []
			self.lib_ctx = c_void_p ( self.lib.init_generator(c_char_p(output_name)) )

			if self.lib_ctx.value == None or self.lib_ctx == 0:
				logging.error("error in initializing generator")
				fo.close()
				return None
			audio = self.select_ran_music(self.audio)    
			self.set_audio(audio)

			self.add_phase(dest_dir= self.preroll,overlay_text="",
							img_count = 1,min_time=self.preroll_min,
							max_time=self.preroll_max,
							textcolor=self.overlayInfo.color,
							textx=-1,texty=-1,
							shadowcolor=self.overlayInfo.shadowColor,
							shadowx= self.overlayInfo.shadowX,
							shadowy = self.overlayInfo.shadowY)

			self.add_phase(dest_dir= self.main,overlay_text=cKeyWord,
							img_count = self.no_of_main_image,min_time=self.main_min,
							max_time=self.main_max,
							textcolor=self.overlayInfo.color,
							textx=-1,texty=-1,
							shadowcolor=self.overlayInfo.shadowColor,
							shadowx= self.overlayInfo.shadowX,
							shadowy = self.overlayInfo.shadowY)

			if self.close1 != None:
				self.add_phase(dest_dir= self.close1,overlay_text="",
								img_count = 1,min_time=self.close1_min,
								max_time=self.close1_max,
								textcolor=self.overlayInfo.color,
								textx=-1,texty=-1,
								shadowcolor=self.overlayInfo.shadowColor,
								shadowx= self.overlayInfo.shadowX,
								shadowy = self.overlayInfo.shadowY)
			self.add_phase(dest_dir= self.close2,overlay_text=loop,
							img_count = 1,min_time=self.close2_min,
							max_time=self.close2_max,
							textcolor=0x165332,
							textx=-1,texty=10,
							shadowcolor=self.overlayInfo.shadowColor,
							shadowx= 1,
							shadowy = 1)
			self.lib.dinit_generator(self.lib_ctx)

			with self.lock:
				if self.app_thread_exit == 0:
					output_name = output_name.replace("\"","")
					output_name = output_name.replace("\\","/")
					output_name = output_name.replace(" ","")
					
					if cTitle == wx.EmptyString:
						cTitle = "Test Title"
					if cDescription == wx.EmptyString:
						cDescription = "Test Description"
					if cKeyWord == wx.EmptyString:
						cKeyWord = ""

					try:
						uvideo = UploadVideo(file=output_name,
								title=cTitle,
								description=cDescription,
								keywords=cKeyWord,
								edir=self.edir)
						logging.info("Initialising Video Upload")
						uvideo.initialize_upload()
					except Exception, e:
						logging.error("error in uploading video")
						logging.exception(e)
					i += 1
			#closing the file when ffmpeg has used it
			
		fo.close()
	def close(self):
		with self.lock:
			self.app_thread_exit = 1 

#KeyWord="Follow the link",# below or visit http://www.ohiorvcamping.org/rv-sweepstakes.html",
if __name__ == '__main__':
	logging.basicConfig(level=logging.DEBUG)
	os.putenv('VGM_INSTALL_PATH',os.getcwd())
	os.environ['VGM_INSTALL_PATH'] = os.getcwd()
	#start the thread so that Application remain responsive
	video_generator = VideoGenerator(iteration=1,KeyWord="Follow the link,cool RV,here",
										Title="Testing the overlay bug",
										mdfilename=os.path.join("test","mdfilename.txt"),
										audio=os.path.join("test","audio"),
										preroll=os.path.join("test","preroll"),
										main=os.path.join("test","main"),
										close1=os.path.join("test","close1"),
										close2=os.path.join("test","close2"),
										output_dir=os.path.join("test","output"),
										edir=os.path.abspath(os.path.dirname(sys.argv[0]))
										)
	if video_generator.isAlive():                     
		video_generator.join()
